import { reqCartList ,reqAddCartSuccess ,updateChecked ,deleteOne} from '@/api'

const actions = {
    //购物车结算接口
    async getCarList({ commit, dispatch, state, getters }) {
        let result = await reqCartList()
        if (result.code === 200) {
            commit('GETCARLIST', result.data)
        }
    },
    // 修改购物车数量
    async getAddCartNum({ commit, dispatch, state, getters },{skuId,skuNum}){
        let result = await reqAddCartSuccess(skuId,skuNum)
        if(result.code === 200){
            return 'ok'
        }else{
            return Promise.reject(new Error('失败'))
        }
    },
    //修改单数据状态 return Promise
    async getCheckedOne({ commit, dispatch, state, getters },{skuId,isChecked}){
        let result = await updateChecked(skuId,isChecked)
        //返回promise
        if(result.code==200){
            return 'ok'
        }else{
            return Promise.reject(new Error('请求失败'))
        }
    },
    // 删除单项数据 return Promise
    async getDeleteOne({ commit, dispatch, state, getters },skuId){
        let result = await deleteOne(skuId)
        if(result.code === 200){
            return 'ok'
        }else{
            return Promise.reject(new Error('失败'))
        }
    },
    // 删除多项
    getDeleteAll({ commit, dispatch, state, getters }){
        // 创建空数组
        let arr = []
        // 循环当前getters 的数据
        getters.GetterCarList.forEach((item)=>{
            // 判断当前状态被选中的
            if(item.isChecked===1){
                // 派发dispat
                let ps = dispatch('getDeleteOne',item.skuId)
                // 将返回的promise push到数组内
                arr.push(ps)
            }
        });
        //将当前的结果返回通过all方法返回
        return Promise.all(arr)
    },
    // 修改多项
    updateCheckedAll({ commit, dispatch, state, getters },isChecked){
        let arr = []
        getters.GetterCarList.forEach(async item=>{
            let ps =  dispatch('getCheckedOne',{skuId:item.skuId,isChecked})
            arr.push(ps)
        })
        return Promise.all(arr)
    }

}
const state = {
    carList: {}
}
const getters = {
    GetterCarList(state) {
        return (state.carList[0] || {}).cartInfoList || []
    }
}

const mutations = {
    GETCARLIST(state, payload) {
        state.carList = payload
    }
}

export default {
    actions,
    state,
    getters,
    mutations
}